package com.example.utils.cmdutils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class CmdUtils {

    /**
     * 命令行运行
     * @return
     */
    public static String runTimeProcess(String shell){
        StringBuilder stringBuilder=new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(shell);
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            process.waitFor();
            while ((line = input.readLine()) != null){
                System.out.println(line);
                stringBuilder.append(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 多组命令
     * @param cmds
     * @return
     */
    public static String runTimeProcess(String[] cmds){
        StringBuilder stringBuilder=new StringBuilder();
        //String[] cmd = new String[]{"/bin/sh","-c", " ps -ef"};
        try {
            Process ps = Runtime.getRuntime().exec(cmds);
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
